﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ServerNodeGui
{
	public partial class OpenBatchTemplateDialog : Form
	{
		public OpenBatchTemplateDialog()
		{
			InitializeComponent();
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			txtFileName.Text = ServerGuiSettings.Default.LastTemplateFileName;
			txtComments.Text = ServerGuiSettings.Default.LastTemplateComments;
			txtOutDir.Text = ServerGuiSettings.Default.LastOutputDir;
			this.Icon = CommonLib.CommonResources.CommonIcon;
		}

		private String comments;
		public String Comments
		{
			get
			{
				return comments;
			}
		}
		private ServerNodeLib.BatchTemplate template;
		public ServerNodeLib.BatchTemplate Template
		{
			get
			{
				return this.template;
			}
		}
		private String outputDir;
		public String OutputDirectory
		{
			get
			{
				return this.outputDir;
			}
		}

		private void btnBrowse_Click(object sender, EventArgs e)
		{
			OpenFileDialog ofd = new OpenFileDialog();
			ofd.Multiselect = false;
			ofd.Filter = ServerGuiSettings.Default.TemplateFileFilter;
			if (ofd.ShowDialog() == DialogResult.OK)
			{
				txtFileName.Text = ofd.FileName;
			}
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
			this.Close();
		}

		private void btnOk_Click(object sender, EventArgs e)
		{
			try
			{
				if (System.IO.File.Exists(txtFileName.Text) == false)
					throw new ArgumentException(String.Format(GuiResources.TemplateFileNotExist, txtFileName.Text));
				outputDir = txtOutDir.Text;
				if (outputDir == null)
					outputDir = String.Empty;
				using (System.IO.StreamReader reader = new System.IO.StreamReader(txtFileName.Text))
				{
					System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(ServerNodeLib.BatchTemplate));
					this.template = s.Deserialize(reader) as ServerNodeLib.BatchTemplate;
					this.comments = txtComments.Text;
					if (comments == null)
						comments = String.Empty;
					reader.Close();
				}
				ServerGuiSettings.Default.LastTemplateComments = this.comments;
				ServerGuiSettings.Default.LastTemplateFileName = txtFileName.Text;
				this.DialogResult = DialogResult.OK;
				this.Close();
			}
			catch (InvalidOperationException ex)
			{
				lblError.Text = "Error: " + ex.Message;
			}
			catch (ArgumentException ex)
			{
				lblError.Text = "Error: " + ex.Message;
			}
		}
	}
}
